/*
 * @Author: your name
 * @Date: 2021-12-17 18:20:07
 * @LastEditTime: 2022-04-29 11:16:39
 * @LastEditors: Please set LastEditors
 * @Description: 请求成功拦截
 * @FilePath: \blog-api\src\shared\interceptor\transform.interceptor.ts
 */

import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Logger } from '../../utils/log4js';
import { Request } from 'express'

interface Message {
    message?: string
}

interface Response<T> {
    data: T
}

@Injectable()
export class TransformInterceptor<T extends Message> implements NestInterceptor<T, Response<T>> {
    intercept(context: ExecutionContext, next: CallHandler<T>): Observable<any> {
        const req = context.getArgByIndex(1).req;

        return next.handle().pipe(
            map(data => {
                const logFormat = ` <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<请求成功的返回值
                    Request original url: ${req.originalUrl}
                    Method: ${req.method}
                    IP: ${req.ip}
                    User: ${JSON.stringify(req.user)}
                    Response data:\n ${JSON.stringify(data)}
                <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<`;
                // Logger.info(logFormat);

                return {
                    data: data,
                    code: 200,
                    message: data.message || '请求成功'
                }
            })
        )
    }
}